#include "StdAfx.h"
#include "GameController.h"

//===========================================================================
IGameController * CreateGameController( void )
{
    return new GameController();
}

//===========================================================================
GameController::GameController( void )
    : m_board(  NULL    )
    , m_human(  NULL    )
    , m_ai(     NULL    )
    , m_state(  ES_NONE )
{
}

//===========================================================================
GameController::~GameController( void )
{
    this->Cleanup();
}

//===========================================================================
void GameController::Initialize( void )
{
    this->m_board = CreateBoard();
    CreatePlayers(
        this->m_board,
        this->m_human,
        this->m_ai
    );

    Piece bottom = ES_BOTTOM == this->m_ai->GetSide()
                 ? this->m_ai->GetPieceType()
                 : this->m_human->GetPieceType();
    Piece top    = !bottom;
    this->m_board->Initialize(
        top,
        bottom
    );

    this->m_state = ES_NONE;
}

//===========================================================================
void GameController::Play( void )
{
    this->m_state = ES_PLAYING;

    vector< IPlayer * > players;
    players.push_back( this->m_human );
    players.push_back( this->m_ai );
    
    auto itEnd = players.end();
    while( true ) {
        auto it = players.begin();
        for( ; it != itEnd; it++ ) {
            this->m_board->Draw();

            IPlayer * player = *it;
            if( !player->OnTurn() ) {
                this->m_state = ES_GAME_OVER;
                break;
            }
        }

        if( this->IsGameOver() ) {
            cout << endl << "GAME OVER" << endl;            
            break;
        }
    }
}

//===========================================================================
void GameController::Release( void )
{
    GameController::Release( this );
}

//===========================================================================
void GameController::Release(
    GameController * game
) {
    if( game )
        delete game;
}

//===========================================================================
bool GameController::IsGameOver( void )
{
    return ES_GAME_OVER == this->m_state;
}

//===========================================================================
void GameController::Cleanup( void )
{
    if( this->m_human ) {
        this->m_human->Release();
        this->m_human = NULL;
    }

    if( this->m_ai ) {
        this->m_ai->Release();
        this->m_ai = NULL;
    }

    if( this->m_board ) {
        this->m_board->Release();
        this->m_board = NULL;
    }
}